home *** CD-ROM | disk | FTP | other *** search
- Path: news.halcyon.com!usenet
- From: normanb@halcyon.com (Norm Bryar)
- Newsgroups: comp.lang.c++
- Subject: Re: [Q] Dynamically allocating memory for a char*
- Date: Sat, 20 Jan 1996 19:19:52 GMT
- Organization: Northwest Nexus Inc.
- Message-ID: <4drf80$ih1@news.halcyon.com>
- References: <4dmn1i$10t@walrus2.walrus.com>
- NNTP-Posting-Host: blv-pm3-ip2.halcyon.com
- X-Newsreader: Forte Free Agent 1.0.82
-
- fjordao@walrus.com (Felipe Jordao) wrote:
-
- >Hi,
-
- >I have a question about allocating memory for a string as it's passed
- >in by the user...(I know this is wrong, but the idea of it ...)
-
- >cin >> malloc(sizeof(infile)); :0
-
- >Here is the actual code
- >----------------------------------------------------------------------
-
- >main()
- >{
- > ifstream InputFile; // Input file stream
- > ofstream OutputFile; // Output file stream
- > ...
- > OpenFiles(InputFile, OutputFile);
- > ...
- >}
-
-
- >void OpenFiles(ifstream& InputFile, ofstream& OutputFile)
- >{
- > char infile[30]; // <---- RIGHT HERE. this works as it is,
- > char outfile[30]; // but I would like to use
- > // char *infile, *outfile. When
- > // I try, I have not found a way to
- > // dynamically allocate memory when the
- > // user inputs the file. I know I can
- > // use something like infile = new char[X]
- > // but that still leave me with the X limit.
-
- > cout << "Enter the path and filename of" << endl
- > << "the input file (*.csv): ";
- > cin >> infile; // I would like to allocate memory right after
- > // user inputs the name of the file. If I use
- > // *infile and leave it like this it crashes
- > // because of unallocated space
-
- > InputFile.open(infile); // Test to see if the input file opens
- > if (!InputFile) {
- > cerr << "Cannot open input file!" << endl;
- > exit(1);
- > }
-
-
- > cout << "Enter the path and filename of" << endl // get output file
- > << "the output file (*.bcp): "; // from user
- > cin >> outfile;
-
- > OutputFile.open(outfile); // Test to see if the output file opens
- > if (!OutputFile) {
- > cerr << "Cannot open output file!" << endl;
- > exit(1);
- > }
- >}
-
- If input truly came from a file (not interactive), you'd load the size
- of the string first, then new char[ thesize ].
-
- For interactive input, either reserve blocks of _MAX_PATH like you've
- been doing or perhaps you can do something with cin.get() to retrieve
- one character at a time and realloc as you read.
-
- --Norm
-
-